package org.apereo.cas;

import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.apereo.cas.Test.UserDaoTest;
import org.apereo.cas.authentication.AuthenticationHandlerExecutionResult;
import org.apereo.cas.authentication.MessageDescriptor;
import org.apereo.cas.authentication.PreventedException;
import org.apereo.cas.authentication.UsernamePasswordCredential;
import org.apereo.cas.authentication.handler.support.AbstractUsernamePasswordAuthenticationHandler;
import org.apereo.cas.authentication.principal.PrincipalFactory;
import org.apereo.cas.entity.User;
import org.apereo.cas.services.ServicesManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.stereotype.Component;

import javax.security.auth.login.AccountException;
import javax.security.auth.login.FailedLoginException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author cheng
 */

@Component
public class CustomUsernamePasswordAuthentication extends AbstractUsernamePasswordAuthenticationHandler {

//    @Value("${cas.authn.jdbc.query[0].driverClass}")
    private String driver = "com.mysql.cj.jdbc.Driver";

//    @Value("${cas.authn.jdbc.query[0].url}")
    private String url = "jdbc:mysql://localhost:3306/intel-platdb?useUnicode=true&characterEncoding=utf8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=Asia/Shanghai&allowMultiQueries=true\n";

//    @Value("${cas.authn.jdbc.query[0].user}")
    private String username = "root";

//    @Value("${cas.authn.jdbc.query[0].password}")
    private String password = "root";


    public CustomUsernamePasswordAuthentication(String name, ServicesManager servicesManager, PrincipalFactory principalFactory, Integer order) {
        super(name, servicesManager, principalFactory, order);
    }

    @Override
    protected AuthenticationHandlerExecutionResult authenticateUsernamePasswordInternal(UsernamePasswordCredential usernamePasswordCredential, String s) throws GeneralSecurityException, PreventedException {
        String username = usernamePasswordCredential.getUsername();
        String password = usernamePasswordCredential.getPassword();
        System.out.println("username : " + username);
        System.out.println("password : " + password);

//        // JDBC模板依赖于连接池来获得数据的连接，所以必须先要构造连接池
////        DriverManagerDataSource dataSource = new DriverManagerDataSource();
////        dataSource.setDriverClassName(driver);
////        dataSource.setUrl(url);
////        dataSource.setUsername(username);
////        dataSource.setPassword(password);
////        // 创建JDBC模板
////        JdbcTemplate jdbcTemplate = new JdbcTemplate();
////        jdbcTemplate.setDataSource(dataSource);
////        String sql = "SELECT * FROM egin_sys_user WHERE login_name = ?";
////        User info = (User) jdbcTemplate.queryForObject(sql, new Object[]{username}, new BeanPropertyRowMapper(User.class));
////        System.out.println("database username : " + info.getLoginName());
////        System.out.println("database password : " + info.getUserPassword());
////
////        if (info == null) {
////            throw new AccountException("Sorry, username not found!");
////        }

        UserDaoTest userDaoTest = new UserDaoTest();
        User info=userDaoTest.getUser(username);


        //密码
//        String upassword = new SimpleHash("md5", password, ByteSource.Util.bytes(username), 6).toString();
//        password = new SimpleHash("md5", password, ByteSource.Util.bytes(username), 6).toString();

        if (!info.getUserPassword().equals(password)) {
            throw new FailedLoginException("Sorry, password not correct!");
        } else {
            //可自定义返回给客户端的多个属性信息
            HashMap<String, Object> returnInfo = new HashMap<>();
            returnInfo.put("age", info.getAge());
            final List<MessageDescriptor> list = new ArrayList<>();
            return createHandlerResult(usernamePasswordCredential,
                    this.principalFactory.createPrincipal(username, returnInfo), list);
        }
    }

//    public static void main(String[] args) {
//        String upassword = new SimpleHash("md5", "000000", ByteSource.Util.bytes("admin"), 6).toString();
//        System.out.println(upassword);
//    }



}
